package com.paipaideli.ui.login;

import android.content.Intent;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.BuildConfig;
import com.paipaideli.R;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.pullrefresh.TStatusView;
import com.paipaideli.common.utils.JsutmentUtil;
import com.paipaideli.common.utils.StringUtil;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.common.utils.preferrnces.FastData;
import com.paipaideli.ui.MainActivity;
import com.paipaideli.ui.webView.WebAcyivity;

import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by 注册页面
 */
public class RegisterActivity extends BasePresenterActivity {

    Unbinder unbinder;
    @BindView(R.id.top_back)
    RelativeLayout top_back;
    @BindView(R.id.top_title)
    TextView top_title;
    @BindView(R.id.register_phone)
    EditText register_phone;
    @BindView(R.id.register_sms)
    EditText register_sms;
    @BindView(R.id.btn_register_sms)
    Button btn_register_sms;
    @BindView(R.id.et_register_onepwd)
    EditText et_register_onepwd;
    @BindView(R.id.et_register_twopwd)
    EditText et_register_twopwd;
    @BindView(R.id.et_register_tjm)
    EditText et_register_tjm;
    @BindView(R.id.image_register_check)
    ImageView image_register_check;
    @BindView(R.id.rel_register_check)
    LinearLayout rel_register_check;
    @BindView(R.id.tv_register_ys)
    TextView tv_register_ys;
    @BindView(R.id.btn_register_register)
    Button btn_register_register;
    @BindView(R.id.tv_register_login)
    TextView tv_register_login;
    @BindView(R.id.bg_statusview)
    TStatusView bg_statusview;

    private boolean flag = true;

    @Override
    public int getContentView() {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);
        top_title.setText("注册");

        //隐私权限的选中
        addDisposable(RxView.clicks(rel_register_check)
                .throttleFirst(0, TimeUnit.SECONDS)
                .subscribe(o -> {
                    if (flag) {
                        flag = false;
                        image_register_check.setImageResource(R.mipmap.login_check);
                    } else {
                        flag = true;
                        image_register_check.setImageResource(R.mipmap.login_nocheck);
                    }
                }));

        //返回
        top_back.setOnClickListener(o ->
                finish()
        );

        //获取验证码
        RxView.clicks(btn_register_sms).subscribe(o -> {
            getSms();
        }, throwable -> {

        });

        //隐私协议
        RxView.clicks(tv_register_ys).subscribe(o -> {
            WebAcyivity.open(getCurrentActivity(), BuildConfig.h5 + "agreement.html","隐私协议");
           // ToastUtil.show("隐私协议");
        }, throwable -> {
        });

        //登录页面
        RxView.clicks(tv_register_login).subscribe(o -> {
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            startActivity(intent);
        }, throwable -> {
        });

        //注册
        addDisposable(RxView.clicks(btn_register_register)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    register();
                }));
    }

    private void getSms() {
        String phone = register_phone.getText().toString();
        if (!StringUtil.isEmpty(phone)) {
            if (JsutmentUtil.isMobileTrue(register_phone.getText().toString())) {
                JSONObject requestData = new JSONObject();
                try {
                    requestData.put("phone", phone);
                    requestData.put("type", "1");
                } catch (Exception e) {
                    e.getMessage();
                }
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
                bg_statusview.showLoading();
                Api.getInstanceGson().sms(body)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(request -> {
                            if (request.getCode().equals("200")) {
                                addDisposable(Flowable.interval(1, TimeUnit.SECONDS)
                                        .take(60)
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .doOnComplete(() -> {
                                            btn_register_sms.setClickable(true);
                                            btn_register_sms.setText("点击再次发送");
                                        })
                                        .subscribe(aLong -> {
                                            btn_register_sms.setText("已发送" + (59 - aLong) + "秒");
                                            btn_register_sms.setClickable(false);
                                        }, throwable -> {
                                            Log.e(TAG, "error", throwable);
                                        }));
                                bg_statusview.finish();
                                ToastUtil.show("验证码发送成功！");
                            } else {
                                bg_statusview.finish();
                                ToastUtil.show(request.getMessage());
                            }
                        }, throwable -> {
                            bg_statusview.finish();
                        });
            } else {
                ToastUtil.show("请输入正确的手机号码");
            }
        } else {
            ToastUtil.show("请输入手机号码");
        }
    }

    private void register() {
        String phone = register_phone.getText().toString().trim();
        String yzm = register_sms.getText().toString().trim();
        String onePwd = et_register_onepwd.getText().toString().trim();
        String twoPwd = et_register_twopwd.getText().toString().trim();
        String tjm = et_register_tjm.getText().toString().trim();
        if (!StringUtil.isEmpty(phone)) {
            if (JsutmentUtil.isMobileTrue(phone)) {
                if (!StringUtil.isEmpty(yzm)) {
                    if (!StringUtil.isEmpty(onePwd)) {
                        if (!StringUtil.isEmpty(twoPwd)) {
                            if (!StringUtil.isEmpty(twoPwd)) {
                                if (onePwd.equals(twoPwd)) {
                                    if (flag) {
                                        ToastUtil.show("请同意隐私协议！");
                                    } else {
                                        JSONObject requestData = new JSONObject();
                                        try {
                                            requestData.put("phone",phone);
                                            requestData.put("smsCode",yzm);
                                            requestData.put("password",onePwd);
                                            requestData.put("referralCode",tjm);
                                        } catch (Exception e) {
                                            e.getMessage();
                                        }
                                        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
                                        bg_statusview.showLoading();
                                        Api.getInstanceGson().register(body)
                                                .observeOn(AndroidSchedulers.mainThread())
                                                .subscribe(request -> {
                                                    if (request.code.equals("200")) {
                                                        FastData.setUsername(phone);
                                                        FastData.setUserPwd(onePwd);
                                                        FastData.setIsLogin(true);
                                                        FastData.setToken(request.data.token);
                                                        FastData.setReferralCode(request.data.referralCode);
                                                        MainActivity.openSingleTop(RegisterActivity.this);
                                                        finish();
                                                        bg_statusview.finish();
                                                        ToastUtil.show(request.msg);
                                                    } else {
                                                        bg_statusview.finish();
                                                        ToastUtil.show(request.msg);
                                                    }
                                                }, throwable -> {
                                                    bg_statusview.finish();
                                                    Log.e(TAG, "error", throwable);
                                                });
                                    }
                                } else {
                                    ToastUtil.show("两次密码输入不一致，请重新输入！");
                                }
                            } else {
                                ToastUtil.show("请输入密码！");
                            }
                        } else {
                            ToastUtil.show("请输入密码！");
                        }
                    } else {
                        ToastUtil.show("请输入密码！");
                    }
                } else {
                    ToastUtil.show("请输入验证码！");
                }
            } else {
                ToastUtil.show("请输入正确的手机号码");
            }
        } else {
            ToastUtil.show("请输入手机号码");
        }
    }
}
